package com.enhe.gck.fg;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.communal.PublicEntity;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.communal.PublicReturn;
import com.enhe.gck.item.OrderHWANE16677Item;
import com.enhe.gck.item.RechargeHWANE16698Item;
import com.enhe.gck.pojo.*;
import com.kuangkie.carbon.common.AggregateVO;
import com.kuangkie.carbon.enun.SortDirection;
import com.kuangkie.carbon.fg.*;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.FGRecord;
import com.kuangkie.carbon.record.RecordQueryProConJunctionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import com.kuangkie.carbon.record.FGRecordComplexus;
import com.kuangkie.carbon.record.ProRecord;
import com.enhe.gck.CarbonBaseConstant; //模型Code
import com.enhe.gck.CarbonEnumKeyValue; //枚举字典信息
import com.enhe.gck.CarbonRelationType; //关系类型Code
import com.enhe.gck.item.CustomerHWANE16644Item; // 模型属性Code
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Repository(value = "hwane16644366042330866425862")
public class CustomerHWANE16644BNB implements SecondRoundImproveFuncGroup, FetchFuncGroup {
	@Resource
	private ConfigHWANE16627BNB configHWANE16627BNB;
	@Override
	public void secondImprove(FuncGroupContext context, ProRecord proRecord, FGRecordComplexus recordComplexus,
			ImproveResultFactory improveResultFactory) {
		Customer customer=proRecord.getBean(Customer.class);
        // 去空格
        String customerName = customer.getName().trim();
        customer.setName(customerName);
        improveResultFactory.getCurrentProRecordOpsBuilder()
                .putAttribute(CustomerHWANE16644Item.基本属性组_客户名称,customerName);
        if(StrUtil.isBlank(customer.getType())){
			PublicMethod.returnMessage(improveResultFactory, PublicReturn.ORDER_10);
		}

		if(proRecord.isNew()){
			if (checkCustomerNameExist(improveResultFactory, customer.getName(), null)) {
                return;
            }
			//默认值
			improveResultFactory
					.getCurrentProRecordOpsBuilder()
					.putAttribute(CustomerHWANE16644Item.基本属性组_是否删除,CarbonEnumKeyValue.是否_否_f);
		} else {
            if (checkCustomerNameExist(improveResultFactory, customer.getName(), customer.getRecordCode())) {
                return;
            }
        }
		if(String.valueOf(CarbonEnumKeyValue.是否_否_f).equals(customer.getIsDelete())){
			if(String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_散户_sh).equals(customer.getType())){
				AggregateVO aggregateVO = PublicMethod.query(CarbonBaseConstant.客户管理_khgl)
						.addNotEqual(CarbonBaseConstant.COLUMN_ABP0001, customer.getRecordCode())
						.addEqual(CustomerHWANE16644Item.基本属性组_客户名称, customer.getName())
						.addEqual(CustomerHWANE16644Item.基本属性组_是否删除, CarbonEnumKeyValue.是否_否_f)
						.goBack().queryCount();
				if(aggregateVO!=null&&aggregateVO.getCount()>0){
					PublicMethod.returnMessage(improveResultFactory,PublicReturn.Customer_1);
					return;
				}
			}
		}

		if(String.valueOf(CarbonEnumKeyValue.是否_是_s).equals(customer.getIsDelete())){
			if(String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_经销商_jxs).equals(customer.getType())||
					String.valueOf(CarbonEnumKeyValue.客户管理_客户类型_散户_sh).equals(customer.getType())){
				if(isHaveMoney(customer.getRecordCode(),improveResultFactory)){
					return;
				}
			}
		}
	}

    /**
     * 检查客户名称是否存在，客户名称不允许重复
     */
	private static boolean checkCustomerNameExist(ImproveResultFactory improveResultFactory, String customerName, String ignoreId) {
		// 校验客户名称是否存在
		RecordQueryProConJunctionFactory query = PublicMethod.query(CarbonBaseConstant.客户管理_khgl);
		query.addEqual(CustomerHWANE16644Item.基本属性组_客户名称, customerName);
        if (StrUtil.isNotBlank(ignoreId)) {
            query.addNotEqual(CarbonBaseConstant.COLUMN_ABP0001, ignoreId);
        }
		List<Customer> customers = query.goBack().queryBeans(Customer.class);
		if (!CollectionUtils.isEmpty(customers)) {
			PublicMethod.returnMessage(improveResultFactory, PublicReturn.Customer_2);
			return true;
		}
		return false;
	}

	@Override
	public void fetchImprove(FuncGroupContext funcGroupContext, FGRecord fgRecord, FetchResultFactory fetchResultFactory) {
		if(fgRecord.getLongValue(CustomerHWANE16644Item.基本属性组_客户类型)==CarbonEnumKeyValue.客户管理_客户类型_经销商_jxs){
			setData(fgRecord.getRecordCode(),CarbonRelationType.RR_订单记录_客户名称_客户管理,fetchResultFactory);
		}
		if(fgRecord.getLongValue(CustomerHWANE16644Item.基本属性组_客户类型)==CarbonEnumKeyValue.客户管理_客户类型_散户_sh){
			setData(fgRecord.getRecordCode(),CarbonRelationType.RR_订单记录_散户_客户管理,fetchResultFactory);
		}
	}

	/**
	 * 赋值
	 * @param id 客户
	 * @param code 散户 or 经销商
	 * @param fetchResultFactory
	 */
	private void setData(String id,long code,FetchResultFactory fetchResultFactory){
		String key=PublicConstant.redisHeaderKhCq+id;
		String value=PublicMethod.dataPermanent.getIfPresent(key);
		if(value==null){
			List<BigDecimal> list=getRechargeCount(id,code);
			value=list.get(0).toPlainString()+PublicConstant.SEMICOLON+list.get(1).toPlainString()+PublicConstant.SEMICOLON+list.get(2).toPlainString();
			PublicMethod.dataPermanent.put(key,value);
		}
		String[] list=value.split(PublicConstant.SEMICOLON);
		fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可用余额,list[0]);
		fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可下单量,list[1]);
		fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可下袋数_袋_,list[2]);
	}

	private void setFromData(List<BigDecimal> list,FetchResultFactory fetchResultFactory,String value){
		fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可下单量,list.get(0));
		fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可用余额,list.get(1));
		if(value!=null){
			BigDecimal oneWeight=new BigDecimal(value);
			if(oneWeight.compareTo(BigDecimal.ZERO)>0){
				fetchResultFactory.getRecordOpsBuilder().putAttribute(CustomerHWANE16644Item.基本属性组_可下袋数_袋_,PublicMethod.divideBigDecimal(list.get(0),value,0,RoundingMode.DOWN).toPlainString());
			}
		}
	}

	@Deprecated
	public List<BigDecimal> getWeight(FGRecord fgRecord,long code){
		List<BigDecimal> rlist=new ArrayList<>();
		BigDecimal sumWeight=BigDecimal.ZERO;
		BigDecimal haveWeight=BigDecimal.ZERO;
		BigDecimal money=BigDecimal.ZERO;
		RecordQueryProConJunctionFactory jf = CarbonPanel
				.getRecordQueryFactory(CarbonBaseConstant.充值记录_czjl).getProConJunctionFactory()
				.addGreaterThan(RechargeHWANE16698Item.基本属性组_可用余额,0);
		//同步检索关系客户下的订单
		jf.getRelationCriterionFactory(CarbonBaseConstant.客户管理_khgl)
				.setInRelationTypes(CarbonRelationType.RR_充值记录_客户名称_客户管理)
				.setInGuestCodes(fgRecord.getRecordCode());
		List<Recharge> list=jf.goBack().addSortItem(PublicMethod.createTimeStr(CarbonBaseConstant.充值记录_czjl), SortDirection.ASC).queryBeans(Recharge.class);
		if(list!=null){
			for (Recharge x:list){
				log.info("QAQ客户下的充值记录:{}t", JSON.toJSON(x));
				money=money.add(BigDecimal.valueOf(x.getAvailableBalance()));

				RecordQueryProConJunctionFactory heTong=CarbonPanel
						.getRecordQueryFactory(CarbonBaseConstant.合同单价_htdj)
						.getProConJunctionFactory();
				heTong.getRelationCriterionFactory(CarbonBaseConstant.充值记录_czjl)
						.setInRelationTypes(CarbonRelationType.RR_合同单价_充值名称_充值记录)
						.setInGuestCodes(x.getRecordCode())
				;
				List<Univalence> nowO=heTong.goBack().queryBeans(Univalence.class);
				if(nowO==null ||nowO.isEmpty()){
					log.info("QAQ无可用单价记录:");
				}else {
					Univalence hetong=nowO.get(0);
					BigDecimal sum=BigDecimal.valueOf(x.getAvailableBalance());
					BigDecimal unit=BigDecimal.valueOf(hetong.getUnit());
					BigDecimal availableWeight=PublicMethod.divideBigDecimal(sum,unit,PublicConstant.weightDecimals, RoundingMode.DOWN);
					log.info("QAQ可用单价记录 {}, {}, {}:",sum,unit,availableWeight);
					sumWeight=sumWeight.add(availableWeight);
				}
			}

			RecordQueryProConJunctionFactory orderListS = CarbonPanel
					.getRecordQueryFactory(CarbonBaseConstant.订单记录_ddjl).getProConJunctionFactory()
					.addEqual(OrderHWANE16677Item.基本属性组_是否作废,CarbonEnumKeyValue.是否_否_f)
					.addEqual(OrderHWANE16677Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f);
			orderListS.getRelationCriterionFactory(CarbonBaseConstant.客户管理_khgl)
					.setInRelationTypes(code)
					.setInGuestCodes(fgRecord.getRecordCode());
			List<Order> orderList =orderListS.goBack().queryBeans(Order.class);
			if(orderList!=null){
				for (Order order : orderList) {
					if(!String.valueOf(PublicConstant.OrderStateOver).equals(order.getState())){
						haveWeight=PublicMethod.addBigDecimal(haveWeight,order.getWeight());
					}
				}
			}
		}
		rlist.add(sumWeight.subtract(haveWeight));
		rlist.add(money);
		return rlist;
	}

	public List<BigDecimal> getRechargeCount(String id,long code){
		List<BigDecimal> rlist=new ArrayList<>();
		BigDecimal money=BigDecimal.ZERO;
		BigDecimal sumWeight=BigDecimal.ZERO;
		BigDecimal haveWeight=BigDecimal.ZERO;

		BigDecimal sumBagsWeight=BigDecimal.ZERO;
		BigDecimal sumBags=BigDecimal.ZERO;
		BigDecimal haveBags=BigDecimal.ZERO;

		RecordQueryProConJunctionFactory jf = CarbonPanel
				.getRecordQueryFactory(CarbonBaseConstant.充值记录_czjl).getProConJunctionFactory()
				.addGreaterThan(RechargeHWANE16698Item.基本属性组_可用余额,0)
				.addEqual(RechargeHWANE16698Item.基本属性组_作废,false)
				;
		//同步检索关系客户下的订单
		jf.getRelationCriterionFactory(CarbonBaseConstant.客户管理_khgl)
				.setInRelationTypes(CarbonRelationType.RR_充值记录_客户名称_客户管理)
				.setInGuestCodes(id);
		List<Recharge> list=jf.goBack().addSortItem(PublicMethod.createTimeStr(CarbonBaseConstant.充值记录_czjl), SortDirection.ASC).queryBeans(Recharge.class,3);
		if(list!=null){
			//老
//			for (Recharge recharge:list){
//				if(recharge!=null&&recharge.getUnivalence()!=null&&recharge.getUnivalence().getGoods()!=null){
//					if(recharge.getUnivalence().getUnit()>0){
//						BigDecimal kxdl=PublicMethod.divideBigDecimal(recharge.getAvailableBalance(),recharge.getUnivalence().getUnit(),PublicConstant.weightDecimals,RoundingMode.DOWN);
//						money=money.add(BigDecimal.valueOf(recharge.getAvailableBalance()));
//						if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(recharge.getUnivalence().getGoods().getType())){
//							sumBagsWeight=sumBagsWeight.add(kxdl);
//						}else {
//							sumWeight=PublicMethod.addBigDecimal(sumWeight,kxdl);
//						}
//					}
//				}
//			}
			//新
			Map<String, Map<BigDecimal, PublicEntity.RechargeUnit>> map=PublicMethod.integration(list);
			for (Map.Entry<String, Map<BigDecimal, PublicEntity.RechargeUnit>> mapF : map.entrySet()) {
				Goods goods=PublicMethod.getInfo(CarbonBaseConstant.产品管理_cpgl, mapF.getKey(),Goods.class);
				if(goods!=null){
					boolean isDai= String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(goods.getType());
					for (Map.Entry<BigDecimal, PublicEntity.RechargeUnit> mapS : mapF.getValue().entrySet()) {
						PublicEntity.RechargeUnit recharge=mapS.getValue();
						BigDecimal sum=recharge.getAvailableBalanceSum();
						BigDecimal unit=mapS.getKey();
						BigDecimal availableWeight=PublicMethod.divideBigDecimal(sum,unit,PublicConstant.weightDecimals, RoundingMode.DOWN);
						money=money.add(sum);
						if(isDai){
							sumBagsWeight=sumBagsWeight.add(availableWeight);
						}else {
							sumWeight=sumWeight.add(availableWeight);
						}
					}
				}
			}

			String value=configHWANE16627BNB.getConfigValueOneWeight();
			sumBags=PublicMethod.divideBigDecimal(sumBagsWeight,value,0, RoundingMode.DOWN);
			RecordQueryProConJunctionFactory orderListS = CarbonPanel
					.getRecordQueryFactory(CarbonBaseConstant.订单记录_ddjl).getProConJunctionFactory()
					.addEqual(OrderHWANE16677Item.基本属性组_是否作废,CarbonEnumKeyValue.是否_否_f)
					.addEqual(OrderHWANE16677Item.基本属性组_是否退货,CarbonEnumKeyValue.是否_否_f)
					.addNotEqual(OrderHWANE16677Item.基本属性组_状态,PublicConstant.OrderStateOver)
					//新 二次榜结算
					// order- 170(加待归还) 392(加待归还) 434(加待归还) 439(加待归还) 710(加待归还) 1130(加待归还) 1162(加待归还)
					// weight- 294(加待归还) 381(加待归还)
					.addNotEqual(OrderHWANE16677Item.基本属性组_状态,CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk)
					;
			orderListS.getRelationCriterionFactory(CarbonBaseConstant.客户管理_khgl)
					.setInRelationTypes(code)
					.setInGuestCodes(id);
			List<Order> orderList =orderListS.goBack().queryBeans(Order.class);
			if(orderList!=null){
				for (Order order : orderList) {
					if(String.valueOf(CarbonEnumKeyValue.订单记录_类型_袋装_dz).equals(order.getType())){
						if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(order.getState())){
							haveBags=PublicMethod.addBigDecimal(haveBags,order.getActualWeight()!=null? PublicMethod.divideBigDecimal(order.getActualWeight(),value,0, RoundingMode.DOWN):0);
						}else {
							haveBags=PublicMethod.addBigDecimal(haveBags,order.getWeight()!=null?PublicMethod.divideBigDecimal(order.getWeight(),value,0, RoundingMode.DOWN):0);
						}
					}else {
						if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_待归还卡_dghk).equals(order.getState())){
							haveWeight=PublicMethod.addBigDecimal(haveWeight,order.getActualWeight()==null?"0":order.getActualWeight());
						}else {
							haveWeight=PublicMethod.addBigDecimal(haveWeight,order.getWeight()==null?"0":order.getWeight());
						}
					}
				}
			}
		}
		rlist.add(money);
		rlist.add(PublicMethod.subtractBigDecimal(sumWeight,haveWeight,PublicConstant.weightDecimals,null));
		rlist.add(PublicMethod.subtractBigDecimal(sumBags,haveBags,0,null));
		return rlist;
	}

	@Deprecated
	public void test(List<Recharge> list){
		Map<BigDecimal, PublicEntity.RechargeUnit> map=new LinkedHashMap<>();
		list.forEach(r->{
			BigDecimal unit=new BigDecimal(String.valueOf(r.getUnivalence().getUnit()));
			if(map.containsKey(unit)){
				map.get(unit).getList().add(r);
			}else {
				PublicEntity.RechargeUnit info=new PublicEntity.RechargeUnit();
				List<Recharge> listZ=new ArrayList<>();
				listZ.add(r);
				info.setList(listZ);
				info.setAvailableBalanceSum(new BigDecimal(String.valueOf(r.getAvailableBalance())));
				map.put(unit,info);
			}
		});
		map.forEach((k,v)->{
			System.out.println(k+":"+v);
		});
	}

	public boolean isHaveMoney(String is,ImproveResultFactory improveResultFactory){
		boolean result=false;
		RecordQueryProConJunctionFactory jf = PublicMethod.query(CarbonBaseConstant.充值记录_czjl)
				.addGreaterThan(RechargeHWANE16698Item.基本属性组_可用余额,0)
				.addEqual(RechargeHWANE16698Item.基本属性组_作废,false)
				;
		//同步检索关系客户下的订单
		jf.getRelationCriterionFactory(CarbonBaseConstant.客户管理_khgl)
				.setInRelationTypes(CarbonRelationType.RR_充值记录_客户名称_客户管理)
				.setInGuestCodes(is);
		List<String> listId=jf.goBack().queryCodes();
		if(listId!=null&& !listId.isEmpty()){
			result=true;
			PublicMethod.returnMessage(improveResultFactory,PublicReturn.Recharge_5);
		}
		return result;
	}
}
